/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 版本: 苏州公安统一用户管理平台1.0
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名:IndexController.java
 * <p>
 * 类产生时间: 2012-6-10 下午9:07:35
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 苏州公安统一用户管理平台
 * <p>
 * 所在部门: 电信/国土——技术二部
 * <p>
 * <p>
 */
package com.oceansoft.core.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hui.platform.system.exception.HuiException;
import com.hui.platform.system.utility.StringUtil;
import com.oceansoft.core.jxkh.domain.Signin;
import com.oceansoft.core.jxkh.service.ISigninService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.oceansoft.common.util.encrypt.Blowfish;
import com.oceansoft.core.common.constant.Constant;
import com.oceansoft.core.common.util.CommonUtilCache;
import com.oceansoft.core.dao.util.SQLUtil;
import com.oceansoft.core.domain.Message;
import com.oceansoft.core.domain.SysDept;
import com.oceansoft.core.domain.SysResource;
import com.oceansoft.core.domain.SysUser;
import com.oceansoft.core.service.ISysDeptService;
import com.oceansoft.core.service.ISysResourceService;
import com.oceansoft.core.service.ISysSsoLogService;
import com.oceansoft.core.service.ISysUserService;
import com.oceansoft.core.service.IUUMSRoleService;

/**
 * 个人登录首页
 *
 * @author chenw
 *
 */
@Controller
@RequestMapping("/profile")
public class ProfileController {
	private static final Logger logger = Logger.getLogger(ProfileController.class.getName());
	@Resource
	private ISysUserService userService;
	@Resource
	private ISysDeptService sysDeptService;
	@Resource
	private ISysResourceService sysResourceService;
	@Resource
	private IUUMSRoleService roleService;
	@Resource
	private  ISysSsoLogService  ssoLogService;

	@Resource
	private ISigninService signinService;
	@RequestMapping("login")
	public String loginSys() {
		return "profile/login";
	}

	@RequestMapping(value = "admin", method = RequestMethod.GET)
	public String gotoIndex(ModelMap model,HttpServletRequest request) {
		SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
		//获取当前用户是否签到0未签到，1已签到，2已签退
		int i = 0;
		try {
			i =signinService.checkIsSign(user.getPoliceNum());
		} catch (HuiException e) {
			e.printStackTrace();
		}
		if(i>0){
			Signin signin = signinService.findByPoliceNum(user.getPoliceNum());
			model.addAttribute("signin",signin);
		}
		model.addAttribute("issign",i);
		model.addAttribute("LOGIN_TIME", new SimpleDateFormat("yyyy年MM月dd日 E").format(new Date()));
		return "profile/admin";
	}

	@RequestMapping("/auth")
	public void login(HttpServletRequest request, SysUser fromVO, ModelMap model) {
		Message msg = new Message("登录成功！");
		Object obj = request.getSession().getAttribute(Constant.LOGIN_USER);
		//obj = null;
		if (null == obj) {
			if (null != fromVO && StringUtils.hasText(fromVO.getPoliceNum())) {
				SysUser user = userService.findUserByPoliceNum(fromVO.getPoliceNum());
				if (user == null) {
					msg.setStatus(Constant.RESULT_FAILD);
					msg.setBody("该用户不存在！");
				} else {
					if (!fromVO.getPassword().equals(
							new Blowfish(Constant.ENCRYPT_SALT).decryptString(user.getPassword()))) {
						msg.setStatus(Constant.RESULT_FAILD);
						msg.setBody("用户名或密码错误！");
						msg.setExtentData(new Blowfish(Constant.ENCRYPT_SALT).decryptString(user.getPassword()));
					} else {
						// 屏蔽个人信息
						user.setPassword(null);
						user.setIdCard(null);
						user.setUip(request.getRemoteHost());

						List<SysDept> depts = sysDeptService.findDeptByDeptId(user.getDeptId());
						SysDept dept = depts.size() > 0 ? depts.get(0) : new SysDept();
						if (null != dept.getDeptId()) {
							int max_len = dept.getDeptId().length();
							int end_index = (dept.getDeep() * 2 + 6) > max_len ? max_len : (dept.getDeep() * 2 + 6);

							user.setShortDeptId(dept.getDeptId().substring(0, end_index));
						}
						//user.setDeptName(dept.getAlias());
						//user.setSysDept(dept);
						// 初始化用户登录信息
						initLoginInfo(model, request, user);

						try {
							// 记录登录日志
							ssoLogService.saveLog(user);
							// "统一用户管理平台");
						} catch (Exception e) {
							logger.log(Level.SEVERE, "写入登录日志异常！" + e.getMessage());
							msg.setStatus(Constant.RESULT_FAILD);
							msg.setBody("登录出错，请稍候再试！");
						}

						// 加载当前用户资源列表
						Map<String, ArrayList<SysResource>> map = sysResourceService.findUserResources(user
								.getPoliceNum());
						user.setUserResources(map);
						request.getSession().setAttribute(Constant.LOGIN_USER, user);


						SQLUtil u = new SQLUtil();
						List<SysResource> rlist = u.list("SELECT T3.*  FROM T_SYS_RESOURCE T3 WHERE   EXISTS (SELECT T2.*, ROWNUM RUM FROM T_SYS_ROLE_RESOURCE T2 WHERE T2.ROLE_ID IN (SELECT T.ROLEID FROM T_SYS_USER_ROLE T WHERE T.USERID = ? )AND T2.RES_ID = T3.RESID) ORDER BY deep,ordernum",SysResource.class, user.getPoliceNum());

						request.getSession().setAttribute("rlist", rlist);

					}
				}
			} else {
				msg.setStatus(Constant.RESULT_FAILD);
				msg.setBody("登录输入信息有误！");
			}
		}else
		{
			SysUser user = (SysUser)obj;
			//判断是否进分局系统
			if(!user.getDeptId().startsWith("320500"))
			{
				msg.setTitle("1");
			}
		}
		model.addAttribute("msg", msg);
	}

	private String getParentIdByRole(HttpServletRequest request,SysUser user) {
		// 读取角色
		Map<String, Object> roles = roleService.findRoleByUser(user.getPoliceNum());
		String deptName="";
			if((roles.containsKey("2"))){//admin
				//parentId= parentId.substring(0,4)+"00000000";
			}else if((roles.containsKey("11"))){//cjgb_roleid处级干部需要控制钻取当前部门，找到当前所在部门的名称
				SysDept dept = sysDeptService.findByDeptId(user.getDeptId());
				deptName = dept.getName();
			}else if((roles.containsKey("10"))){//zhz_roleid
				//parentId= parentId.substring(0,6)+"000000";
			}
		return deptName;
	}

	/**
	 * 安全退出系统
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("exit")
	String exitSys(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(Constant.LOGIN_USER);
		if (null != obj) {
			request.getSession().setAttribute(Constant.LOGIN_USER, null);
			request.getSession().setMaxInactiveInterval(0);
			request.getSession().invalidate();
		}
		return "redirect:/";
	}

	/**
	 * 初始化登录人员会话信息
	 *
	 * @param model
	 * @param request
	 * @param user
	 */
	private void initLoginInfo(ModelMap model, HttpServletRequest request,
							   SysUser user) {
		request.getSession().setAttribute("user", user);
		request.getSession().setAttribute(Constant.LOGIN_USER, user);
		// 用户角色
		// 读取角色
		Map<String, Object> roles = roleService.findRoleByUser(user
				.getPoliceNum());
		request.getSession().setAttribute(Constant.SESSION_ROLOES, roles);
		// 判断是否是管理员
		Object o = CommonUtilCache.getItem("ctx");
		String a = (String) ((ServletContext) o).getAttribute("admin_roleid");
		if (roles.containsKey(a)) {
			request.getSession().setAttribute("isadmin", "1");
		} else {
			request.getSession().setAttribute("isadmin", "0");
		}
		// 判断单位管理员角色
		String dept_roleid = (String) ((ServletContext) o)
				.getAttribute("cjgb_roleid");
		if (roles.containsKey(dept_roleid)) {
			request.getSession().setAttribute("iscjgb", "1");
		} else {
			request.getSession().setAttribute("iscjgb", "0");
		}
		// 判断单位管理员角色
		String zhz_roleid = (String) ((ServletContext) o)
				.getAttribute("zhz_roleid");
		if (roles.containsKey(zhz_roleid)) {
			request.getSession().setAttribute("iszhz", "1");
		} else {
			request.getSession().setAttribute("iszhz", "0");
		}
		// 判断民警角色
		String mj_roleid = (String) ((ServletContext) o)
				.getAttribute("mj_roleid");
		if (roles.containsKey(mj_roleid)) {
			request.getSession().setAttribute("ismj", "1");
		} else {
			request.getSession().setAttribute("ismj", "0");
		}
	}

	@RequestMapping("/gotochangepwd.html")
	public String gotoChangePwd() {
		return "profile/changepwd";
	}



	@RequestMapping("/sso")
	public String sso(HttpServletRequest request, ModelMap model,HttpServletResponse response) {
		String jh = request.getParameter("jh");
		if(StringUtils.hasText(jh)){
			SysUser user = userService.findUserByPoliceNum(jh);
			if(null!=user){
				// 屏蔽个人信息
				user.setPassword(null);
				user.setIdCard(null);
				user.setUip(request.getRemoteHost());

				List<SysDept> depts = sysDeptService.findDeptByDeptId(user.getDeptId());
				SysDept dept = depts.size() > 0 ? depts.get(0) : new SysDept();
				if (null != dept.getDeptId()) {
					int max_len = dept.getDeptId().length();
					int end_index = (dept.getDeep() * 2 + 6) > max_len ? max_len : (dept.getDeep() * 2 + 6);

					user.setShortDeptId(dept.getDeptId().substring(0, end_index));
				}
				user.setDeptName(dept.getAlias());
				//user.setSysDept(dept);
				// 初始化用户登录信息
				initLoginInfo(model, request, user);
				//判断是否进分局系统
				if(!user.getDeptId().startsWith("320500"))
				{
					model.addAttribute("jh",user.getPoliceNum());
					return "profile/login4";
				}
				try {
					// 记录登录日志
					ssoLogService.saveLog(user);
					// "统一用户管理平台");
				} catch (Exception e) {
					logger.log(Level.SEVERE, "写入登录日志异常！" + e.getMessage());
				}

				// 加载当前用户资源列表
				Map<String, ArrayList<SysResource>> map = sysResourceService.findUserResources(user
						.getPoliceNum());
				user.setUserResources(map);
				request.getSession().setAttribute(Constant.LOGIN_USER, user);

				return "profile/admin_brk";
			}
			model.addAttribute("data","该用户不存在!");
			return "profile/login";
		}
		model.addAttribute("data","该用户不存在!");
		return "profile/login";
	}
	@RequestMapping(value="index.html")
	public String index(HttpServletRequest request,ModelMap model) {
		SysUser user = (SysUser) request.getSession().getAttribute(Constant.LOGIN_USER);
		//parentId，这个用来饼图的部门ID
		String deptName = "";
		//这里判断一下，如果是管理员，那么就是顶级，如果是指挥长，就是前6位+000000，如果是部门管理员，就是前8位+0000，
		deptName = getParentIdByRole(request,user);

		model.addAttribute("deptName",deptName);
		return "profile/index";
	}

}
